package com.ssm.test.proxytest;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

interface Animal{
    void run();
}

class Tiger implements Animal{
    String name;
    public Tiger(String name){
        this.name = name;
    }
    @Override
    public void run() {
        System.out.println("I am a Tiger,Run");
    }
}

public class JDKProxy implements InvocationHandler {
    private Object myObject;
    public JDKProxy(Object obj){
        myObject = obj;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        before();
        Object object = method.invoke(this.myObject,args);
        after();
        return object;//返回实体类
    }

    private void after() {
        System.out.println("代理后置增强");
    }

    private void before() {
        System.out.println("代理前置增强");
    }
    public <T> T getProxy(){
        return (T) Proxy.newProxyInstance(//动态创建一个Animal接口的代理类
                myObject.getClass().getClassLoader(),//代理的实体类的类加载器
                myObject.getClass().getInterfaces(),//代理的实体类的接口
                this);//我们的代理类
    }
    public static <T> T getmyProxy(Object object){
        return(T) new JDKProxy(object).getProxy();//封装代理方法
    }

    public static void main(String[] args) {
        Animal tiger=JDKProxy.getmyProxy(new Tiger("Tiger"));
        tiger.run();
    }
}

